local _BagItem = require "UI/Bag/bag_item"


local BagView = BagView or BaseClass(BaseView)
local math_ceil = math.ceil
local math_floor = math.floor

function BagView:__init()
	self.base_file = "Bag"
	self.layout_file = "BagView"
	self.model = BagModel:GetInstance()
	self.item_list = {}
	self.load_callback = function()
		self:LoadSuccess()
		self:InitEvent()
		self:SetData()
	end
	self.close_callback = function()
		self:Remove()
	end
end

function BagView:LoadSuccess()
	self.close_btn = self.transform:Find("layout/closeBtn").gameObject
	self.info_btn = self.transform:Find("layout/infoBtn").gameObject
	self.content = self.transform:Find("layout/ScrollView/Viewport/Content")
end

function BagView:InitEvent()
	local function onClickHandler(target, x, y)
		if target == self.close_btn then
			self:Close()
		elseif target == self.info_btn then
			self.model:Fire(BagModel.EVENT_NAME.OPEN_BAG_SMALL_VIEW)
		end
	end
	AddClickEvent(self.close_btn, onClickHandler)
	AddClickEvent(self.info_btn, onClickHandler)
end

function BagView:SetData()
	local list = self.model:GetFakeBagDatas()
	local len = #list
	local size = getSizeDelta(self.content)
	setSizeDelta(self.content, size.x, (len / 5) * 86)
	for index, data in pairs(list) do
		local item = self.item_list[index]
		if not item then
			item = _BagItem.New(self.content)
			self.item_list[index] = item
		end
		local col = math_ceil(index / 5) - 1
		local row = (index % 5)
		item:SetAnchoredPosition(row * 98 + 10, -col * 86)
	end
end

function BagView:Remove()
	for _, item in pairs(self.item_list) do
		if item then
			item:DeleteMe()
			item = nil
		end
	end
	self.item_list = {}
end

return BagView